/*
 * @(#)AbstractSolrService.java 2012-01-09
 *
 * Copyright 2011 北龙中网（北京）科技有限责任公司. All rights reserved.
 */
package cn.shangjia.shop.service.v2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import cn.shangjia.common.dao.support.Page;
import cn.shangjia.common.domain.Domain;
import cn.shangjia.common.util.BeanUtils;
import cn.shangjia.common.util.ReflectUtils;
import cn.shangjia.common.util.StringUtils;
import cn.shangjia.search.common.bean.AbstractSolrBean;
import cn.shangjia.search.common.client.ISolrClient;
import cn.shangjia.search.common.client.SolrQueryParams;
import cn.shangjia.search.common.client.SolrResponse;

/**
 *
 * @author <a href="mailto:jinzhongze@knet.cn">jinzhongze</a>
 * @version 1.0, 2012-01-09 09:32:56
 * @since 1.0
 */
public abstract class AbstractSolrService<SOLRBEAN extends AbstractSolrBean, T extends Domain> implements SolrService<SOLRBEAN, T> , ApplicationContextAware{
	
	private ISolrClient solrClient;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		String solrClientName = getSolrClientName();
		if (StringUtils.isEmpty(solrClientName)) {
			throw new IllegalArgumentException("[solrClientName]  - the object argument must be Empty ! ");
		}
		solrClient = applicationContext.getBean(solrClientName, ISolrClient.class);
	}
	
	protected abstract String getSolrClientName();
	
	public final ISolrClient getSolrClient() {
		return solrClient;
	}
	
	@SuppressWarnings({ "unchecked" })
	protected Class<SOLRBEAN> getSOLRBEANClass() {
		Class<SOLRBEAN> clazz = ReflectUtils.getSuperClassGenricType(this.getClass(), 0);
		return clazz;
	}
	
	@Override
	public Page<T> getPageObject(Map<String, Object> params, int pageNo, int pageSize) {
		return getPageObject(params, pageNo, pageSize, "createDate", "desc");
	}
	
	@Override
	public Page<T> getPageObject(Map<String, Object> params, int pageNo, int pageSize, String field, String desc) {

		SolrQueryParams queryParams = new SolrQueryParams();
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				Object value = params.get(key);
				if (key != null && value != null)
//					queryParams.addFilterQuery(key + ":" + value);
					queryParams.addFilterQuery(key, value);
			}
		}
		queryParams.setPage(pageNo);
		queryParams.setPageSize(pageSize);
		
		if (!StringUtils.isEmpty(field)) {
			if (StringUtils.isEmpty(desc)) {
				desc = "asc";
			} else {
				desc = desc.toLowerCase();
			}
			queryParams.addSort(field, desc);
		}
		
		SolrResponse response = solrClient.query(queryParams, getSOLRBEANClass());
		List<SOLRBEAN> solrResult = response.getData();
		
		List<T> result = new ArrayList<T>();
		if (solrResult != null && !solrResult.isEmpty()) {
			for (SOLRBEAN bean : solrResult) {
				T tmp = getNewT();
				BeanUtils.copyProperties(tmp, bean);
				result.add(tmp);
			}
		}
		
		Page<T> page = new Page<T>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page.setResult(result);
		page.setTotalCount(response.getRowsCount());
		return page;
	
	}
	
	@Override
	public T getObject(String id) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		return getObject(params);
	}

	@Override
	public T getObject(Map<String, Object> params) {
		SolrQueryParams queryParams = new SolrQueryParams();
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				Object value = params.get(key);
				if (key != null && value != null)
//					queryParams.addFilterQuery(key + ":" + value);
					queryParams.addFilterQuery(key , value);
			}
		}
		SolrResponse response = solrClient.query(queryParams, getSOLRBEANClass());
		List<SOLRBEAN> solrResult = response.getData();
		if (solrResult == null || solrResult.isEmpty())
			return null;
		SOLRBEAN tmp = solrResult.get(0);
		T result = getNewT();
		BeanUtils.copyProperties(result, tmp);
		return result;
	}
	
	
	@SuppressWarnings("unchecked")
	private T getNewT() {
		T tmp;
		Class<T> clazz = ReflectUtils.getSuperClassGenricType(this.getClass(), 1);
		try {
			tmp = clazz.newInstance();
		} catch (Exception e) {
			throw new RuntimeException("要返回的对象 . 没有  默认 构造方法.  不是个有效 javabean");
		}
		return tmp;
	}
}
